package com.mindata.blockchain.socket.common.listener;

import com.mindata.blockchain.socket.body.base.InstructionsBody;
import com.mindata.blockchain.socket.client.PacketSender;
import com.mindata.blockchain.socket.packet.BlockPacket;
import com.mindata.blockchain.socket.packet.PacketBuilder;
import com.mindata.blockchain.socket.packet.PacketType;
import com.mindata.blockchain.socket.common.event.TransactionMsgEvent;
import com.mindata.blockchain.socket.common.msg.InstructionMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class InstructionMsgListener {
    @Resource
    private PacketSender packetSender;
    private Logger logger = LoggerFactory.getLogger(InstructionMsgListener.class);

    @EventListener(TransactionMsgEvent.class)
    public void transactionbroadcast(TransactionMsgEvent transactionMsgEvent) {
        InstructionMsg txMsg = (InstructionMsg) transactionMsgEvent.getSource();
        if (txMsg.getInstructions().isEmpty()) {
//            logger.error("{}收到转发的交易消息：\\n{}",this, txMsg);
            return;
        } else {
            logger.error("{}收到转发的交易消息：\\n{}", this, txMsg);
        }
        //群发消息，通知别的节点，我已收到并验证该交易
        BlockPacket blockPacket = new PacketBuilder<>().setType(PacketType.TRANSACTION).setBody(new
                InstructionsBody(txMsg)).build();
        //广播给所有人
        packetSender.sendGroup(blockPacket);
//        logger.warn("{}广播消息", this);
    }
}
